const express = require('express');
const sqlite3 = require('sqlite3').verbose();
const cors = require('cors');
const multer = require('multer');
const XLSX = require('xlsx');
const path = require('path');
const fs = require('fs');

const app = express();
const PORT = 3002;

// 中间件 - 配置 CORS 允许所有域名访问
app.use(cors({
  origin: '*',  // 允许所有域名访问
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Cache-Control'],
  credentials: false  // 不需要凭据时设为 false，提高兼容性
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务 - 提供图片访问
const imagesPath = path.join(__dirname, 'images');
console.log('📁 Images目录路径:', imagesPath);
app.use('/questionChat/images', (req, res, next) => {
  console.log('🖼️ 静态图片请求:', req.path);
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}, express.static(imagesPath));

// 文件上传配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
});
const upload = multer({ storage: storage });

// SQLite数据库配置
const dbPath = path.join(__dirname, 'question_collect.db');

// 创建数据库连接
let db;

// 初始化数据库
function initDatabase() {
  return new Promise((resolve, reject) => {
    db = new sqlite3.Database(dbPath, (err) => {
      if (err) {
        console.error('❌ SQLite数据库连接失败:', err);
        reject(err);
      } else {
        console.log('✅ SQLite数据库连接成功');
        
        // 检查数据库是否为空，如果为空则初始化
        db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='user_table'", (err, row) => {
          if (err) {
            reject(err);
          } else if (!row) {
            // 数据库为空，执行初始化脚本
            const sqlScript = fs.readFileSync(path.join(__dirname, '../sql/question_collect_sqlite.sql'), 'utf8');
            db.exec(sqlScript, (err) => {
              if (err) {
                console.error('❌ 数据库初始化失败:', err);
                reject(err);
              } else {
                console.log('✅ 数据库初始化成功');
                resolve();
              }
            });
          } else {
            console.log('✅ 数据库已存在，跳过初始化');
            resolve();
          }
        });
      }
    });
  });
}

// 包装SQLite查询为Promise
function runQuery(sql, params = []) {
  return new Promise((resolve, reject) => {
    db.all(sql, params, (err, rows) => {
      if (err) {
        reject(err);
      } else {
        resolve(rows);
      }
    });
  });
}

// 包装SQLite插入/更新/删除为Promise
function runStatement(sql, params = []) {
  return new Promise((resolve, reject) => {
    db.run(sql, params, function(err) {
      if (err) {
        reject(err);
      } else {
        resolve({ 
          lastID: this.lastID, 
          changes: this.changes,
          insertId: this.lastID,
          affectedRows: this.changes
        });
      }
    });
  });
}

// 注册接口
app.post('/questionChat/api/register', async (req, res) => {
  try {
    const { username, password, real_name, age, gender } = req.body;
    
    // 验证必填字段
    if (!username || !password || !real_name || !age || !gender) {
      return res.json({
        success: false,
        message: '请填写完整的注册信息'
      });
    }
    
    // 验证年龄范围
    if (age < 10 || age > 100) {
      return res.json({
        success: false,
        message: '年龄必须在10-100岁之间'
      });
    }
    
    // 验证性别
    if (!['男', '女'].includes(gender)) {
      return res.json({
        success: false,
        message: '性别只能选择男或女'
      });
    }
    
    // 检查用户名是否已存在
    const existingUser = await runQuery(
      'SELECT id FROM user_table WHERE username = ?',
      [username]
    );
    
    if (existingUser.length > 0) {
      return res.json({
        success: false,
        message: '用户名已存在，请选择其他用户名'
      });
    }
    
    // 创建新用户
    const result = await runStatement(
      'INSERT INTO user_table (username, password, real_name, age, gender, isadmin, allow_node) VALUES (?, ?, ?, ?, ?, 0, 0)',
      [username, password, real_name, age, gender]
    );
    
    res.json({
      success: true,
      message: '注册成功',
      data: {
        id: result.insertId,
        username,
        real_name,
        age,
        gender,
        isadmin: 0,
        allow_node: 0
      }
    });
    
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 登录接口
app.post('/questionChat/api/login', async (req, res) => {
  try {
    console.log('🔐 登录请求:', req.body);
    const { username, password } = req.body;
    
    if (!username || !password) {
      console.log('❌ 缺少用户名或密码');
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }
    
    console.log('🔍 查询数据库用户:', username);
    const rows = await runQuery(
      'SELECT * FROM user_table WHERE username = ? AND password = ?',
      [username, password]
    );
    console.log('📊 查询结果:', rows.length > 0 ? '找到用户' : '用户不存在');
    
    if (rows.length > 0) {
      const user = rows[0];
      res.json({
        success: true,
        data: {
          id: user.id,
          username: user.username,
          real_name: user.real_name,
          isadmin: user.isadmin,
          allow_node: user.allow_node,
          age: user.age,
          gender: user.gender
        },
        token: 'token_' + user.id + '_' + Date.now()
      });
    } else {
      res.json({
        success: false,
        message: '用户名或密码错误'
      });
    }
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 获取章节脚本
app.get('/questionChat/api/scripts/:nodenum', async (req, res) => {
  try {
    const nodenum = req.params.nodenum;
    
    const rows = await runQuery(
      'SELECT * FROM script_table WHERE nodenum = ? ORDER BY answernum, id',
      [nodenum]
    );
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('获取脚本错误:', error);
    res.status(500).json({
      success: false,
      message: '获取脚本失败'
    });
  }
});

// 获取脚本文本内容（前端实现打字机效果）
app.get('/questionChat/api/script-text/:scriptId', async (req, res) => {
  try {
    const scriptId = req.params.scriptId;
    
    // 获取脚本内容
    const rows = await runQuery(
      'SELECT content FROM script_table WHERE id = ?',
      [scriptId]
    );
    
    if (rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: '脚本不存在'
      });
    }
    
    const content = rows[0].content || '';
    
    // 直接返回完整内容
    res.json({
      success: true,
      data: {
        content: content,
        length: content.length
      }
    });
    
  } catch (error) {
    console.error('获取脚本内容错误:', error);
    res.status(500).json({
      success: false,
      message: '获取脚本内容失败'
    });
  }
});


// 获取所有脚本（管理员用）
app.get('/questionChat/api/scripts', async (req, res) => {
  try {
    const rows = await runQuery(
      'SELECT * FROM script_table ORDER BY nodenum, answernum, id'
    );
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('获取脚本错误:', error);
    res.status(500).json({
      success: false,
      message: '获取脚本失败'
    });
  }
});

// 创建脚本
app.post('/questionChat/api/scripts', async (req, res) => {
  try {
    const { nodenum, answernum, content, answertype, next_answernum, need_input, img, timer } = req.body;
    
    const result = await runStatement(
      'INSERT INTO script_table (nodenum, answernum, content, answertype, next_answernum, need_input, img, timer) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [nodenum, answernum, content, answertype, next_answernum, need_input || 0, img || null, timer || null]
    );
    
    res.json({
      success: true,
      data: {
        id: result.insertId,
        nodenum,
        answernum,
        content,
        answertype,
        next_answernum,
        need_input: need_input || 0,
        img: img || null,
        timer: timer || null
      }
    });
  } catch (error) {
    console.error('创建脚本错误:', error);
    res.status(500).json({
      success: false,
      message: '创建脚本失败'
    });
  }
});

// 更新脚本
app.put('/questionChat/api/scripts/:id', async (req, res) => {
  try {
    const id = req.params.id;
    const { nodenum, answernum, content, answertype, next_answernum, need_input, img, timer } = req.body;
    
    
    const result = await runStatement(
      'UPDATE script_table SET nodenum = ?, answernum = ?, content = ?, answertype = ?, next_answernum = ?, need_input = ?, img = ?, timer = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [nodenum, answernum, content, answertype, next_answernum, need_input || 0, img || null, timer || null, id]
    );
    
    
    if (result.affectedRows > 0) {
      res.json({
        success: true,
        message: '更新成功'
      });
    } else {
      res.json({
        success: false,
        message: '脚本不存在'
      });
    }
  } catch (error) {
    console.error('更新脚本错误:', error);
    res.status(500).json({
      success: false,
      message: '更新脚本失败'
    });
  }
});

// 删除脚本
app.delete('/questionChat/api/scripts/:id', async (req, res) => {
  try {
    const id = req.params.id;
    
    const result = await runStatement(
      'DELETE FROM script_table WHERE id = ?',
      [id]
    );
    
    if (result.affectedRows > 0) {
      res.json({
        success: true,
        message: '删除成功'
      });
    } else {
      res.json({
        success: false,
        message: '脚本不存在'
      });
    }
  } catch (error) {
    console.error('删除脚本错误:', error);
    res.status(500).json({
      success: false,
      message: '删除脚本失败'
    });
  }
});

// 获取单个用户信息
app.get('/questionChat/api/users/:id', async (req, res) => {
  try {
    const id = req.params.id;
    
    const rows = await runQuery(
      'SELECT id, username, real_name, age, gender, isadmin, allow_node FROM user_table WHERE id = ?',
      [id]
    );
    
    if (rows.length > 0) {
      res.json({
        success: true,
        data: rows[0]
      });
    } else {
      res.json({
        success: false,
        message: '用户不存在'
      });
    }
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户信息失败'
    });
  }
});

// 获取用户列表
app.get('/questionChat/api/users', async (req, res) => {
  try {
    const rows = await runQuery(
      'SELECT id, username, password, real_name, age, gender, isadmin, allow_node, created_at FROM user_table ORDER BY id'
    );
    
    res.json({
      success: true,
      data: rows
    });
  } catch (error) {
    console.error('获取用户错误:', error);
    res.status(500).json({
      success: false,
      message: '获取用户失败'
    });
  }
});

// 更新用户进度
app.put('/questionChat/api/users/:id/progress', async (req, res) => {
  try {
    const id = req.params.id;
    const { allow_node } = req.body;
    
    console.log(`📈 更新用户进度请求: 用户ID=${id}, 新进度=${allow_node}`);
    
    const result = await runStatement(
      'UPDATE user_table SET allow_node = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [allow_node, id]
    );
    
    if (result.affectedRows > 0) {
      console.log(`✅ 用户进度更新成功: 用户ID=${id}, 新进度=${allow_node}`);
      res.json({
        success: true,
        message: '更新成功'
      });
    } else {
      console.log(`❌ 用户进度更新失败: 用户ID=${id} 不存在`);
      res.json({
        success: false,
        message: '用户不存在'
      });
    }
  } catch (error) {
    console.error('更新用户进度错误:', error);
    res.status(500).json({
      success: false,
      message: '更新用户进度失败'
    });
  }
});

// 更新用户记录位置
app.put('/questionChat/api/users/:id/remember-position', async (req, res) => {
  try {
    const id = req.params.id;
    const { node, num } = req.body;
    
    console.log(`📍 更新用户记录位置请求: 用户ID=${id}, 章节=${node}, 问题编号=${num}`);
    
    // 验证参数
    if (typeof node !== 'number' || typeof num !== 'number') {
      return res.json({
        success: false,
        message: '参数格式错误'
      });
    }
    
    if (node < 0 || node > 8 || num < 1) {
      return res.json({
        success: false,
        message: '参数范围错误'
      });
    }
    
    // 获取当前用户的remember_nu
    const userResult = await runQuery(
      'SELECT remember_nu FROM user_table WHERE id = ?',
      [id]
    );
    
    if (userResult.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 解析现有的remember_nu或初始化
    let rememberArray;
    try {
      const currentRememberNum = userResult[0].remember_nu;
      if (currentRememberNum && currentRememberNum.trim() !== '') {
        rememberArray = JSON.parse(currentRememberNum);
      } else {
        // 初始化默认数组
        rememberArray = [
          { node: 0, num: 1 },
          { node: 1, num: 1 },
          { node: 2, num: 1 },
          { node: 3, num: 1 },
          { node: 4, num: 1 },
          { node: 5, num: 1 },
          { node: 6, num: 1 },
          { node: 7, num: 1 },
          { node: 8, num: 1 }
        ];
      }
    } catch (error) {
      console.error('解析remember_num失败:', error);
      // 初始化默认数组
      rememberArray = [
        { node: 0, num: 1 },
        { node: 1, num: 1 },
        { node: 2, num: 1 },
        { node: 3, num: 1 },
        { node: 4, num: 1 },
        { node: 5, num: 1 },
        { node: 6, num: 1 },
        { node: 7, num: 1 },
        { node: 8, num: 1 }
      ];
    }
    
    // 确保数组有正确的结构
    if (!Array.isArray(rememberArray) || rememberArray.length !== 9) {
      rememberArray = [
        { node: 0, num: 1 },
        { node: 1, num: 1 },
        { node: 2, num: 1 },
        { node: 3, num: 1 },
        { node: 4, num: 1 },
        { node: 5, num: 1 },
        { node: 6, num: 1 },
        { node: 7, num: 1 },
        { node: 8, num: 1 }
      ];
    }
    
    // 更新指定章节的记录位置
    const targetIndex = rememberArray.findIndex(item => item.node === node);
    if (targetIndex !== -1) {
      rememberArray[targetIndex].num = num;
    } else {
      // 如果没找到对应节点，添加新的记录
      rememberArray.push({ node, num });
      // 按node排序
      rememberArray.sort((a, b) => a.node - b.node);
    }
    
    // 更新数据库
    const result = await runStatement(
      'UPDATE user_table SET remember_nu = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [JSON.stringify(rememberArray), id]
    );
    
    if (result.affectedRows > 0) {
      console.log(`✅ 用户记录位置更新成功: 用户ID=${id}, 章节=${node}, 问题编号=${num}`);
      res.json({
        success: true,
        message: '记录位置更新成功',
        data: { rememberArray }
      });
    } else {
      res.json({
        success: false,
        message: '更新失败'
      });
    }
  } catch (error) {
    console.error('更新用户记录位置错误:', error);
    res.status(500).json({
      success: false,
      message: '更新记录位置失败'
    });
  }
});

// 获取用户记录位置
app.get('/questionChat/api/users/:id/remember-position', async (req, res) => {
  try {
    const id = req.params.id;
    
    const result = await runQuery(
      'SELECT remember_nu FROM user_table WHERE id = ?',
      [id]
    );
    
    if (result.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 解析remember_nu
    let rememberArray;
    try {
      const currentRememberNum = result[0].remember_nu;
      if (currentRememberNum && currentRememberNum.trim() !== '') {
        rememberArray = JSON.parse(currentRememberNum);
      } else {
        // 返回默认数组
        rememberArray = [
          { node: 0, num: 1 },
          { node: 1, num: 1 },
          { node: 2, num: 1 },
          { node: 3, num: 1 },
          { node: 4, num: 1 },
          { node: 5, num: 1 },
          { node: 6, num: 1 },
          { node: 7, num: 1 },
          { node: 8, num: 1 }
        ];
      }
    } catch (error) {
      console.error('解析remember_num失败:', error);
      rememberArray = [
        { node: 0, num: 1 },
        { node: 1, num: 1 },
        { node: 2, num: 1 },
        { node: 3, num: 1 },
        { node: 4, num: 1 },
        { node: 5, num: 1 },
        { node: 6, num: 1 },
        { node: 7, num: 1 },
        { node: 8, num: 1 }
      ];
    }
    
    res.json({
      success: true,
      data: rememberArray
    });
  } catch (error) {
    console.error('获取用户记录位置错误:', error);
    res.status(500).json({
      success: false,
      message: '获取记录位置失败'
    });
  }
});


// 删除用户
app.delete('/questionChat/api/users/:id', async (req, res) => {
  try {
    const id = req.params.id;
    
    // 首先检查用户是否存在且不是管理员
    const userCheck = await runQuery(
      'SELECT id, isadmin FROM user_table WHERE id = ?',
      [id]
    );
    
    if (userCheck.length === 0) {
      return res.json({
        success: false,
        message: '用户不存在'
      });
    }
    
    if (userCheck[0].isadmin === 1) {
      return res.json({
        success: false,
        message: '不能删除管理员用户'
      });
    }
    
    const result = await runStatement(
      'DELETE FROM user_table WHERE id = ? AND isadmin = 0',
      [id]
    );
    
    if (result.affectedRows > 0) {
      res.json({
        success: true,
        message: '删除成功'
      });
    } else {
      res.json({
        success: false,
        message: '删除失败'
      });
    }
  } catch (error) {
    console.error('删除用户错误:', error);
    res.status(500).json({
      success: false,
      message: '删除用户失败'
    });
  }
});

// 导出Excel接口
app.get('/questionChat/api/export-excel', async (req, res) => {
  try {
    const nodenum = req.query.nodenum;
    console.log('📤 收到Excel导出请求, 章节:', nodenum || '全部');
    
    // 构建查询SQL
    let sql = 'SELECT nodenum, answernum, content, answertype, next_answernum, need_input, img, timer FROM script_table';
    let params = [];
    
    if (nodenum !== undefined && nodenum !== '') {
      sql += ' WHERE nodenum = ?';
      params.push(parseInt(nodenum));
    }
    
    sql += ' ORDER BY nodenum, answernum, id';
    
    // 查询脚本数据
    const rows = await runQuery(sql, params);
    
    console.log(`📊 查询到 ${rows.length} 条数据`);
    
    // 创建Excel工作簿
    const workbook = XLSX.utils.book_new();
    
    // 准备数据
    const data = rows.map(row => ({
      '章节编号': row.nodenum,
      '问题编号': row.answernum,
      '问题内容': row.content || '',
      '问题类型': row.answertype,
      '下一题编号': row.next_answernum,
      '需要输入框': row.need_input || 0,
      '图片路径': row.img || '',
      '计时器': row.timer || ''
    }));
    
    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(data);
    
    // 设置列宽
    worksheet['!cols'] = [
      { wch: 10 },  // 章节编号
      { wch: 10 },  // 问题编号
      { wch: 50 },  // 问题内容
      { wch: 10 },  // 问题类型
      { wch: 12 },  // 下一题编号
      { wch: 12 },  // 需要输入框
      { wch: 30 },  // 图片路径
      { wch: 10 }   // 计时器
    ];
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, '问答脚本');
    
    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });
    
    // 设置响应头
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent('问答脚本导出_' + new Date().toISOString().slice(0, 10) + '.xlsx')}`);
    
    // 发送文件
    res.send(excelBuffer);
    console.log('✅ Excel导出成功');
    
  } catch (error) {
    console.error('Excel导出错误:', error);
    res.status(500).json({
      success: false,
      message: 'Excel导出失败: ' + error.message
    });
  }
});

// 清除所有脚本数据接口
app.delete('/questionChat/api/clear-scripts', async (req, res) => {
  try {
    console.log('🗑️ 收到清除所有脚本数据请求');
    
    const result = await runStatement('DELETE FROM script_table');
    
    console.log(`✅ 清除成功，删除了 ${result.changes} 条数据`);
    
    res.json({
      success: true,
      message: `成功清除 ${result.changes} 条数据`,
      deletedCount: result.changes
    });
    
  } catch (error) {
    console.error('清除数据错误:', error);
    res.status(500).json({
      success: false,
      message: '清除数据失败: ' + error.message
    });
  }
});

// Excel导入接口
app.post('/questionChat/api/import-excel', upload.single('excel'), async (req, res) => {
  try {
    console.log('📤 收到文件上传请求');
    console.log('文件信息:', req.file ? {
      originalname: req.file.originalname,
      filename: req.file.filename,
      size: req.file.size,
      path: req.file.path
    } : '无文件');
    console.log('请求参数:', req.body);
    
    if (!req.file) {
      console.log('❌ 没有接收到文件');
      return res.json({
        success: false,
        message: '请选择Excel文件'
      });
    }
    
    // 读取Excel文件
    const workbook = XLSX.readFile(req.file.path);
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    const data = XLSX.utils.sheet_to_json(worksheet);
    
    // 验证数据格式
    const requiredColumns = ['章节编号', '问题编号', '问题内容', '问题类型', '下一题编号'];
    if (data.length === 0) {
      return res.json({
        success: false,
        message: 'Excel文件为空'
      });
    }
    
    const firstRow = data[0];
    const missingColumns = requiredColumns.filter(col => !(col in firstRow));
    if (missingColumns.length > 0) {
      return res.json({
        success: false,
        message: `缺少必要列: ${missingColumns.join(', ')}`
      });
    }
    
    console.log('📋 Excel表头列:', Object.keys(firstRow).join(', '));
    
    // SQLite不需要显式事务管理，使用serialize确保串行执行
    try {
      // 开始事务
      await runStatement('BEGIN TRANSACTION');
      
      // 导入数据 - 使用INSERT OR REPLACE来处理重复数据
      for (const row of data) {
        await runStatement(
          'INSERT OR REPLACE INTO script_table (nodenum, answernum, content, answertype, next_answernum, need_input, img, timer) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
          [
            row['章节编号'],
            row['问题编号'],
            row['问题内容'] || '',  // 如果为空则使用空字符串
            row['问题类型'],
            row['下一题编号'] ,
            row['需要输入框'] || 0,
            row['图片路径'] || null,  // 可选的图片路径字段
            row['计时器'] || null  // 可选的计时器字段
          ]
        );
      }
      
      // 提交事务
      await runStatement('COMMIT');
      
      res.json({
        success: true,
        message: `成功导入 ${data.length} 条数据`
      });
    } catch (error) {
      // 回滚事务
      await runStatement('ROLLBACK');
      throw error;
    }
    
    // 删除临时文件
    require('fs').unlinkSync(req.file.path);
    
  } catch (error) {
    console.error('Excel导入错误:', error);
    res.status(500).json({
      success: false,
      message: 'Excel导入失败: ' + error.message
    });
  }
});

// 获取章节信息
app.get('/questionChat/api/chapters', async (req, res) => {
  try {
    const chapters = await runQuery(`
      SELECT 
        nodenum,
        COUNT(*) as question_count,
        MIN(id) as first_question_id
      FROM script_table 
      WHERE answertype = 'T'
      GROUP BY nodenum 
      ORDER BY nodenum
    `);
    
    // 添加章节标题
    const chapterTitles = {
      0: 'E0 导入',
      1: 'E1 探寻重复消极思维',
      2: 'E2 认识价值与行动选择',
      3: 'E3 深度了解重复消极思维',
      4: 'E4 做想法的旁观者',
      5: 'E5 探寻自我与生活方向',
      6: 'E6 行动指南',
      7: 'E7 结束'
    };
    
    const chaptersWithTitles = chapters.map(chapter => ({
      nodenum: chapter.nodenum,
      title: chapterTitles[chapter.nodenum] || `第${chapter.nodenum}章`,
      question_count: chapter.question_count,
      description: getChapterDescription(chapter.nodenum)
    }));
    
    res.json({
      success: true,
      data: chaptersWithTitles
    });
  } catch (error) {
    console.error('获取章节信息错误:', error);
    res.status(500).json({
      success: false,
      message: '获取章节信息失败'
    });
  }
});

// 健康检查接口
app.get('/questionChat/api/health', (req, res) => {
  res.json({
    success: true,
    message: '服务正常运行',
    timestamp: new Date().toISOString()
  });
});

// 辅助函数：获取章节描述
function getChapterDescription(nodenum) {
  const descriptions = {
    0: '系统导入和初始化设置',
    1: '识别和分析重复出现的消极思维模式',
    2: '理解个人价值观与行动选择的关系',
    3: '深入了解重复消极思维的特点和影响',
    4: '培养客观观察想法的能力',
    5: '探索自我认知和人生方向',
    6: '制定具体的行动计划和指南',
    7: '总结训练成果并完成课程'
  };
  return descriptions[nodenum] || '心理思维训练';
}

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error);
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  });
});

// 启动服务器
async function startServer() {
  try {
    console.log('🔍 正在初始化数据库...');
    await initDatabase();
    
    app.listen(PORT, () => {
      console.log(`🚀 服务器启动成功，运行在端口 ${PORT}`);
      console.log(`📱 访问地址: http://localhost:${PORT}`);
      console.log(`📁 数据库文件: ${dbPath}`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

startServer();

// 创建uploads目录
const uploadsDir = 'uploads';
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir);
}

// 创建images目录
const imagesDir = 'images';
if (!fs.existsSync(imagesDir)) {
  fs.mkdirSync(imagesDir);
  console.log('✅ Images目录创建成功');
}
